import 'package:flutter_tools/wxlog.dart';
import 'package:flutter_tools/string_extension.dart';
import 'interfaces/refresh_token.dart';
import 'user_info_proxy.dart';

class RefreshTokenProxy {
  static RefreshTokenProxy _instance;

  RefreshTokenProxy._();
  
  RefreshToken _refreshTokenImpl;
  

  static RefreshTokenProxy getInstance() {
    return _instance ??= RefreshTokenProxy._();
  }

  /// 注入refreshtoken的实现
  void injectRefreshTokenImpl(RefreshToken refreshTokenImpl) {
    _refreshTokenImpl = refreshTokenImpl;
  }

  Future<bool> refreshToken() {
    if (null == _refreshTokenImpl)  {
      wxLog("You haven't injected the corresponding instance yet!!!");

      return Future.value(false);
    }

    if (UserInfoProxy.getInstance().getAccessToken().empty)  {
      wxLog("Refresh must provide a non-null AccessToken!!!");

      return Future.value(false);
    }

    return _refreshTokenImpl.refresh();
  }

  void refreshAndHandle(Function doSomeThing) {
    refreshToken().then((value)  {
      if (value && doSomeThing != null) {
        doSomeThing();
      }
    });
  }

}